import os
from PIL import Image
import shutil

working_dir = os.path.dirname(__file__)
jpg_path = f'{working_dir}/jpg/'
pbm_path = f'{working_dir}/pbm/'


def __get_bin_table(threshold=105):
	'''获取灰度转二值的映射表，0 表示白色，1 表示黑色'''
	def append(value):
		return 1 if value < threshold else 0

	return list(map(append, range(256)))


if __name__ == '__main__':
	if os.path.exists(pbm_path):
		shutil.rmtree(pbm_path, ignore_errors=True)

	os.mkdir(pbm_path)

	table = __get_bin_table()

	for index, file in enumerate(os.listdir(jpg_path), start=1):
		input = Image.open(f'{jpg_path}{file}')

		output = input.convert('L').point(table, '1') # .transpose(Image.FLIP_TOP_BOTTOM)
		output_file = pbm_path + '{:04d}.pbm'.format(index)
		output.save(output_file)
